<?php

namespace app\admin\model\dealer;
use think\Model;
/**
 * 分销商用户模型
 * Class Apply
 * @package app\common\model\dealer
 */
class DealerUser extends Model
{
    protected $name = 'dealer_user';



    /**
     * 关联会员记录表
     * @return \think\model\relation\BelongsTo
     */
    public function user()
    {
        return $this->belongsTo('app\admin\model\user\User');
    }

    /**
     * 关联推荐人表
     * @return \think\model\relation\BelongsTo
     */
    public function referee()
    {
        return $this->belongsTo('app\common\model\dealer\Referee', 'user_id','user_id');

    }

    /**
     * 获取分销商用户信息
     * @param $userId
     * @param array $with
     * @return static|null
     * @throws \think\exception\DbException
     */
    public static function detail($userId,$wxapp_id, $with = ['user', 'referee.refreeuser'])
    {

        //分销商表
        $flag = db('dealer_user')->where(['user_id'=>$userId,'is_delete'=>0,'wxapp_id'=>$wxapp_id])->find();

        if(!$flag){
            $dealer_data = [
                'user_id'=>$userId,
                'wxapp_id'=>$wxapp_id,
                'create_time'=>time(),
                'update_time'=>time(),
            ];
            db('dealer_user')->insert($dealer_data);
        }

        $list = self::get($userId, $with);
        if($list['referee']){
            $list['referee']['nickName'] = $list['referee']['refreeuser']['nickName'];
        }


        return $list;
    }




}